const { ipcRenderer } = require('electron');
Vue.use(ELEMENT);
const localData = proxyLocalStorage('data');
localData.count = localData.count || 0;
const app = new Vue({
  el: '#app',
  data: {
    // 用户名
    username: localData.username,
    // 密码
    password: '',
    // 是否展示代理设置页面
    proxyView: false,
    // 代理页面开关设置
    proxy: false,
    // 是否启用代理
    proxySwitch: localData.proxySwitch,
    // 代理地址
    host: localData.host,
    // 代理协议
    protocol: localData.protocol || 'http',
    // 本地快捷密码
    pin: '',
    // 是否开启了快捷登陆
    loginForPin: localData.loginForPin,
    // 登陆按钮显示
    loginButton: '登陆',
    // clickCount
    clickCount: 0,
    // 点击计时器
    timer: null,
  },
  methods: {
    login() {
      if (this.username === '' || this.password === '') {
        this.$message({
          type: 'error',
          message: '请输入账号和密码'
        });
        return;
      }
      if (this.proxySwitch && (!this.protocol || !this.host)) {
        this.$message({
          type: 'error',
          message: '开启服务器配置后请务必指定host'
        });
        return;
      }
      this.loginButton = '登陆中...';
      localData.username = this.username;
      localData.proxySwitch = this.proxySwitch;
      localData.host = this.host;
      localData.protocol = this.protocol;
      const sendData = {
        username: this.username,
        password: this.password,
      };
      if (this.proxySwitch) {
        sendData.host = this.host;
        sendData.protocol = this.protocol;
      }
      ipcRenderer.send('login', sendData);
    },
    async clear() {
      try {
        await this.$msgbox({
          title: '消息',
          message: this.$createElement('p', [
            '此操作将清除本地所有数据(',
            this.$createElement('span', { attrs: { style: "color: red" } }, '包括未上传的更改 '),
            ')且不可恢复，是否继续?',
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        localStorage.removeItem('data');
        localStorage.removeItem('setting');
        this.username = '';
        this.password = '';
        this.proxySwitch = false;
        this.host = '';
        this.protocol = 'http';
        this.loginForPin = false;
      } catch (error) {
        console.log(error);
      }
    },
    dev() {
      if (this.clickCount < 10) {
        this.clickCount ++;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.clickCount = 0;
        }, 2000);
        return;
      }
      clearTimeout(this.timer);
      this.clickCount = 0;
      ipcRenderer.send('devLogin');
    }
  },
  computed: {
    pinWord() {
      return '●'.repeat(this.pin.length);
    }
  }
});

function proxyLocalStorage(key) {
  let data;
  try {
    data = JSON.parse(localStorage.getItem(key)) || {};
  } catch (error) {
    data = {};
  }
  return new Proxy(data, {
    get(target, propKey) {
      try {
        target = JSON.parse(localStorage.getItem(key));
        return target[propKey];
      } catch (error) {
        return undefined;
      }
    },
    set(target, propKey, value) {
      let temp = {};
      try {
        Object.assign(temp, JSON.parse(localStorage.getItem(key)));
      } catch (error) { }
      temp[propKey] = value;
      localStorage.setItem(key, JSON.stringify(temp));
      for (const delKey in target) {
        delete target[delKey];
      }
      Object.assign(target, temp);
    },
    deleteProperty (target, delKey) {
      delete target[delKey];
      localStorage.setItem(key, JSON.stringify(target));
      return true;
    }
  });
}

ipcRenderer.on('loginResult', (_event, { success, type }) => {
  app.loginButton = '登陆';
  if (success) {
    if (type === 'web') {
      localData.encrypted = '';
      localData.loginForPin = false;
      localStorage.removeItem('setting');
    }
    app.pin = '';
    app.password = '';
  } else {
    app.$message({
      type: 'error',
      message: '账号或密码错误！'
    });
    app.pin = '';
    app.password = '';
    localData.count ++;
  }
});

document.onkeydown = function(event) {
  if (!app.loginForPin) {
    return;
  }
  if (event.key === 'Backspace') {
    app.pin = app.pin.substring(0, app.pin.length - 1);
  }
  if ((event.keyCode > 95 && event.keyCode < 106) || (event.keyCode > 47 && event.keyCode < 58)) {
    app.pin += event.key;
    if (app.pin.length >= 4) {
      app.pin = app.pin.substring(0, 4);
      if (localData.count < 5) {
        ipcRenderer.send('login', {
          loginForPin: true,
          pin: app.pin,
          encrypted: localData.encrypted,
        });
      } else {
        app.$message({
          type: 'error',
          message: '账号或密码错误！'
        });
        app.pin = '';
      }
    }
  }
}
